package com.lxs.mall.product.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxs.common.constant.ProductConstant;
import com.lxs.common.dto.MemberPrice;
import com.lxs.common.dto.SkuHasStockDto;
import com.lxs.common.dto.SkuReductionDTO;
import com.lxs.common.dto.SpuBoundsDTO;
import com.lxs.common.dto.es.SkuESModel;
import com.lxs.common.utils.PageUtils;
import com.lxs.common.utils.Query;
import com.lxs.common.utils.R;
import com.lxs.mall.product.entity.*;
import com.lxs.mall.product.feign.CouponService;
import com.lxs.mall.product.feign.ProductUpFeignService;
import com.lxs.mall.product.feign.SearchFeignService;
import com.lxs.mall.product.service.*;
import com.lxs.mall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.lxs.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;
    @Autowired
    SpuImagesService spuImagesService;
    @Autowired
    AttrService attrService;
    @Autowired
    ProductAttrValueService productAttrValueService;
    @Autowired
    SkuInfoService skuInfoService;
    @Autowired
    SkuImagesService skuImagesService;
    @Autowired
    CouponService couponService;
    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    BrandService brandService;
    @Autowired
    ProductUpFeignService productUpFeignService;
    @Autowired
    SearchFeignService searchFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 保存商品的发布信息
     */
    @Override
    @Transactional
    public void saveSpuInfo(SpuInfoVO spuInfoVO) {
        //1,保存spu的基本信息pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfoVO,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        spuInfoEntity.setPublishStatus(0);
        this.save(spuInfoEntity);
        //2,保存spu的详细信息pms_spu_info_desc
        List<String> descripts=spuInfoVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",descripts));
        spuInfoDescService.save(spuInfoDescEntity);

        //3,保存图集信息pms_spu_images
        List<String> images = spuInfoVO.getImages();
        //将每一个图片信息封装成SpuImagesEntity
        List<SpuImagesEntity> imagesEntities = images.stream().map(item -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            spuImagesEntity.setSpuId(spuInfoEntity.getId());
            spuImagesEntity.setImgUrl(item);
            return spuImagesEntity;
        }).collect(Collectors.toList());
        spuImagesService.saveBatch(imagesEntities);
        //4,保存规格参数pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrs = baseAttrs.stream().map(item->{
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            AttrEntity entity= attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(entity.getAttrName());
            productAttrValueEntity.setQuickShow(entity.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrs);
        //5,保存当前的spu对应的所有的sku信息
        List<Skus> skus = spuInfoVO.getSkus();
        if(CollectionUtils.isNotEmpty(skus)){
            skus.forEach(item->{
                //5.1,保存sku的基本信息
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0l);
                List<Images> images1 = item.getImages();
                String defaultImage="";
                for(Images m: images1){
                    if(m.getDefaultImg()==1){
                        //表示默认图片
                        defaultImage=m.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoService.save(skuInfoEntity);
                //5.2,保存sku的图片信息
                List<SkuImagesEntity> skuImagesEntities = images1.stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).filter(img->img.getDefaultImg()==1).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);
                //5.3，保存满减信息，会员价，折扣 mall-sms:sms_sku_ladder, sms_sku_full_reduction, sms_member_price
                SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
                BeanUtils.copyProperties(item,skuReductionDTO);
                skuReductionDTO.setSkuId(skuInfoEntity.getSkuId());
                //设置会员价
                if(CollectionUtils.isNotEmpty(item.getMemberPrice())){
                    List<MemberPrice> members = item.getMemberPrice().stream().map(
                            memberPrice -> {
                                MemberPrice mDto = new MemberPrice();
                                BeanUtils.copyProperties(memberPrice, mDto);
                                return mDto;
                            }).collect(Collectors.toList());
                    skuReductionDTO.setMemberPrice(members);
                }
                R r = couponService.saveFullReductionInfo(skuReductionDTO);
                if(r.getCode()!=0){
                    log.error("调用Coupon服务处理满减、折扣，会员价操作失败...");
                }
                //5.4,保存sku 的销售属性信息，pms_sku_sale_attr_value
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> saleAttrValueEntities = attrs.stream().map(sale -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(sale, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntities);
            });
        }
        //6,保存spud 的积分信息mall-sms:sms_spu_bounds
        Bounds bounds=spuInfoVO.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        BeanUtils.copyProperties(bounds,spuBoundsDTO);
        spuBoundsDTO.setSpuId(spuInfoEntity.getId());
        R r = couponService.saveSpuBounds(spuBoundsDTO);
        if(r.getCode()!=0){
            log.error("调用Coupon服务存储积分信息操作失败");
        }

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        String key = (String) params.get("key");
        String catalogId= (String) params.get("catelogId");
        String brandId = (String) params.get("brandId");
        String status = (String) params.get("status");
        QueryWrapper<SpuInfoEntity> spuInfoEntityQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(key)){
            spuInfoEntityQueryWrapper.and(w->w.eq("id",key)
                    .or().like("spu_name",key)
                    .or().like("spu_description",key));
        }
        if(StringUtils.isNotEmpty(catalogId)&&!"0".equalsIgnoreCase(catalogId)){
            spuInfoEntityQueryWrapper.eq("catalog_id",catalogId);
        }
        if(StringUtils.isNotEmpty(brandId)&& !"0".equalsIgnoreCase(brandId)){
            spuInfoEntityQueryWrapper.eq("brand_id",brandId);
        }
        if(StringUtils.isNotEmpty(status)){
            spuInfoEntityQueryWrapper.eq("publish_status",status);
        }
        //根据查询到的分页信息再查询品牌名称和分类名称
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                spuInfoEntityQueryWrapper
        );
        List<SpuInfoVO> spuInfoVOS = page.getRecords().stream().map(record -> {
            CategoryEntity categoryEntity = categoryService.getById(record.getCatalogId());
            BrandEntity brandEntity = brandService.getById(record.getBrandId());
            SpuInfoVO spuInfoVO = new SpuInfoVO();
            BeanUtils.copyProperties(record,spuInfoVO);
            spuInfoVO.setCatalogName(categoryEntity.getName());
            spuInfoVO.setBrandName(brandEntity.getName());
            return spuInfoVO;
        }).collect(Collectors.toList());
        IPage<SpuInfoVO> pages =new Page<>();
        pages.setRecords(spuInfoVOS);
        pages.setCurrent(page.getCurrent());
        pages.setSize(page.getSize());
        pages.setTotal(page.getTotal());
        pages.setPages(page.getPages());
        return new PageUtils(pages);
    }

    /**
     * 商品上架功能实现，商品相关数据存储到ES中
     *1，根据spuId 查询出相关的信息，封装到对象中
     *2，将封装的数据存储到elasticSearch中，远程调用mall-search
     *3,更新spu的相应状态到数据库中》上架
     * @param spuId
     */
    @Override
    public void up(Long spuId) {
        //1,根据spuId查询出向相关的信息封装到SkuEsModule中
        //根据spuId查找对应的sku信息
        List<SkuInfoEntity> skuInfos = skuInfoService.getSkuInfoBySpuI(spuId);
        //对应的规格参数，根据spuId查询对应的规格参数
        List<SkuESModel.Attrs> attrsModel= getAttrsModel(spuId);
        List<Long> skus = skuInfos.stream().map(sku->sku.getSkuId()).collect(Collectors.toList());
        //需要根据所有的skuID获取库存信息，远程调用mall-ware
        Map<Long,Boolean> skusHasStockMap= getSkusHasStock(skus);
        //封装SkuEsModule数据存储到ES中
        List<SkuESModel> skuESModels = skuInfos.stream().map(item -> {
            SkuESModel model = new SkuESModel();
            // 先实现属性的复制
            BeanUtils.copyProperties(item, model);
            model.setSubTitle(item.getSkuTitle());
            model.setSkuPrice(item.getPrice());
            model.setSkuImg(item.getSkuDefaultImg());

            // hasStock 是否有库存 --》 库存系统查询  一次远程调用获取所有的skuId对应的库存信息
            if (skusHasStockMap == null) {
                model.setHasStock(true);
            } else {
                model.setHasStock(skusHasStockMap.get(item.getSkuId()));
            }
            // hotScore 热度分 --> 默认给0即可
            model.setHotScore(0l);
            // 品牌和类型的名称
            BrandEntity brand = brandService.getById(item.getBrandId());
            CategoryEntity category = categoryService.getById(item.getCatalogId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            model.setCatalogName(category.getName());
            // 需要存储的规格数据
            model.setAttrs(attrsModel);

            return model;
        }).collect(Collectors.toList());
        //2,远程调用mall-search服务，将SkuEsModule数据存储到ES中
        R r = searchFeignService.productStatusUp(skuESModels);
        //3,更新spuId对应的状态，上架
        // 根据对应的状态更新商品的状态
        log.info("----->ES操作完成：{}" ,r.getCode());
        System.out.println("-------------->"+r.getCode());
        if(r.getCode() == 0){
            // 远程调用成功  更新商品的状态为 上架
            baseMapper.updateSpuStatusUp(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            // 远程调用失败
        }

    }

    @Override
    public List<OrderItemSpuInfoVO> getOrderItemSpuInfoBySpuId(Long[] spuIds) {
        List<OrderItemSpuInfoVO> list = new ArrayList<>();
        for (Long spuId : spuIds) {
            OrderItemSpuInfoVO vo = new OrderItemSpuInfoVO();
            SpuInfoEntity spuInfoEntity = this.getById(spuId);
            vo.setId(spuId);
            vo.setSpuName(spuInfoEntity.getSpuName());
            vo.setBrandId(spuInfoEntity.getBrandId());
            vo.setCatalogId(spuInfoEntity.getCatalogId());
            // 根据品牌编号查询品牌信息
            BrandEntity brand = brandService.getById(spuInfoEntity.getBrandId());
            vo.setBrandName(brand.getName());
            CategoryEntity category = categoryService.getById(spuInfoEntity.getCatalogId());
            vo.setCatalogName(category.getName());
            // 获取SPU的图片
            SpuInfoDescEntity descEntity = spuInfoDescService.getById(spuId);
            vo.setImg(descEntity.getDecript());
            list.add(vo);
        }
        // 根据SPUID查询出相关的信息
        return list;
    }

    private Map<Long,Boolean> getSkusHasStock(List<Long> skuIds){
        List<SkuHasStockDto> skusHasStock = null;
        if(skuIds == null && skuIds.size() == 0){
            return null;
        }
        try {
            // 调用远程接口获取对应的信息
            skusHasStock = productUpFeignService.getSkusHasStock(skuIds);
            //skusHasStock.stream().collect(Collectors.toMap(item->{return item.getSkuId();},item->{return item.getHasStock();}));
            Map<Long, Boolean> map = skusHasStock.stream()
                    .collect(Collectors.toMap(SkuHasStockDto::getSkuId, item -> item.getHasStock()));
            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
    private List<SkuESModel.Attrs> getAttrsModel(Long spuId) {

        List<ProductAttrValueEntity>baseAttrs= productAttrValueService.getBaseAttrsBySpuId(spuId);
        List<Long> attrIds = baseAttrs.stream().map(entity -> entity.getAttrId()).collect(Collectors.toList());
        //查询出可以检索的规格参数对应的编号
        List<Long> searchAttrs=attrService.selectSearchAttrIds(attrIds);
        //baseAttrs中筛选出可以检索的属性Id
        List<SkuESModel.Attrs> esModuleAttrs = baseAttrs.stream().filter(item -> searchAttrs.contains(item.getAttrId())).map(item ->
                {
                    SkuESModel.Attrs attrs = new SkuESModel.Attrs();
                    BeanUtils.copyProperties(item, attrs);
                    return attrs;
                }
        ).collect(Collectors.toList());
        return esModuleAttrs;
    }


}
